import { atom } from "jotai";

import type { User } from "@/lib/types";

export const userAtom = atom<{
  user: User | null;
  token: string | null;
  status: "pending" | "finish";
}>({
  user: null,
  token: null,
  status: "pending",
});

export const tokenAtom = atom((get) => get(userAtom).token);

export const isLoginAtom = atom((get) => !!get(userAtom).user);

export const isAuthPendingAtom = atom(
  (get) => get(userAtom).status === "pending",
);

export const authWithTokenAtom = atom(null, async (get, set) => {
  if (__DEV__) {
    await new Promise((r) => setTimeout(r, 1000));
    set(userAtom, { user: {}, token: "", status: "finish" });
    return;
  }

  const token = localStorage.getItem("token");
  if (!token) {
    set(userAtom, (p) => ({ ...p, status: "finish" }));
    return;
  }
  // todo handle login
});
